package TC;
import java.net.*;
import java.io.*;


public class TCSocketTask {
	public String serverAddress = "172.28.2.11";
	public int serverPort = 5002;
	public Socket socket;
	public InputStream in;
	public OutputStream out;
	public String errMsg;
	
	public TCSocketTask() throws UnknownHostException, IOException{
			this.socket = new Socket(serverAddress,5002);
			//socket.setSoTimeout(1000);
			this.in = socket.getInputStream();
			this.out = socket.getOutputStream();
		
	}
	public boolean sendMsg(String Msg){
		try{
			byte[] data = Msg.getBytes();
			out.write(data);
			out.flush();
		}catch(IOException e){
			return false;
		}
		return true;
	}
	public String recMsg() throws IOException{
		int data = 0;
		int Exit = 13;
		StringBuffer stb = new StringBuffer();
		while(data != Exit){
			data = in.read();
			if(data == -1){
				break;
			}
			stb.append((char)data);
		}
		return stb.toString().trim();
		
	}
	public boolean sendTestMsg(){
		String testMsg = "are you ok\r";
		String recTestMsg = "ok";
		String recMsg = null;
		try {
			sendMsg(testMsg);
			recMsg = recMsg();
		} catch (IOException e) {
			return false;
		}
		if(!recMsg.equals(recTestMsg)){
			return false;
		}
		return true;
	}
	public boolean taskPro(String sendMsg){
		String Msg = null;
		String recRes = "Success";
		sendMsg(sendMsg);
		try{
			Msg = recMsg();
		}catch(IOException e){
			return false;
		}
		if(!Msg.equals(recRes)){
			errMsg = Msg;
			return false;
		}
		return true;
	}
	public boolean endTask(){
		String Msg = "end\r";
		String recRes = "Success";
		String recMsg = null;
		sendMsg(Msg);
		try{
			recMsg = recMsg();
		}catch(IOException e){
			return false;
		}
		if(!recMsg.equals(recRes)){
			errMsg = recMsg;
			return false;
		}
		return true;
	}
	public boolean killConn(){
		try{
		in.close();
		out.close();
		socket.close();
		}catch(IOException e){
			return false;
		}
		return true;
	}
}
